package xlink

import (
	"time"

	"gitee.com/xiaoyutab/xgotool/optional/xcache"
	"gitee.com/xiaoyutab/xgotool/xerror"
	"gitee.com/xiaoyutab/xgotool/xstring"
)

// 创建连接信息
func Create(bat *Link) error {
	if _default.DB == nil {
		return xerror.New("数据库未连接")
	}
	if bat.UserId == 0 {
		return xerror.New("连接创建人ID不能为空")
	}
	if bat.Uri == "" {
		return xerror.New("跳转网址不能为空")
	}
	for {
		if bat.Codes == "" {
			bat.Codes = xstring.Random(6)
		}
		if _, err := Find(0, bat.Codes); err != nil {
			break
		}
	}
	if bat.EndDate == "" {
		bat.EndDate = time.Now().AddDate(0, 1, 0).Format(time.DateOnly)
	}
	if bat.CreatedAt == "" {
		bat.CreatedAt = time.Now().Format(time.DateTime)
	}
	bat.UpdatedAt = time.Now().Format(time.DateTime)
	err := _default.DB.Save(bat).Error
	if err != nil {
		return err
	}
	// 缓存写入
	xcache.Remove(xcache.Key("xlink.info", bat.Id))
	xcache.Remove(xcache.Key("xlink.info", bat.Codes))
	return nil
}
